#!/usr/bin/env bash
# escape4sh -- Escape given command-line arguments as a string that
#              is safe to use as input for shells, e.g., sh -c ...
#
# > sh -c "$(escape4sh ARG...)"
##
# Author: Jaeho Shin <netj@cs.stanford.edu>
# Created: 2013-01-24
if [[ $# -gt 0 ]]; then
    # construct a jq expression that applies shell escaping for each given argument
    args=() i=0 jqExpr=
    while [[ $# -gt 0 ]]; do
        let ++i
        args+=(--arg "a$i" "$1"); shift
        jqExpr+='($a'$i'|@sh), '
    done
    jqExpr=${jqExpr%, }
    # then run it
    eval 'jq -n -r "${args[@]}" '\'"[$jqExpr]"' | join(" ")'\'
else
    # without any arguments, escape each line in STDIN
    sed "s/'/'\\\\''/g; s/^/'/; s/\$/'/" | tr '\n' ' ' | sed 's/ $//'
fi
